//
//  HJUserAccountViewModel.swift
//  sinaWeibo
//
//  Created by hjun on 16/3/23.
//  Copyright © 2016年 hjun. All rights reserved.
//

import UIKit

class HJUserAccountViewModel: NSObject {
    
    //单例
    static let sharedInstance: HJUserAccountViewModel = HJUserAccountViewModel()
    
    private override init() {
        super.init()
        
        ///从沙盒里面加载账号
        userAccount = loadUserAccount()
        
    }
    
    ///账号
    var userAccount: HJUserAccount?
    
    
    ///是否登录
    var userLogin:Bool{
        
        get{
            
            return userAccount != nil
        }
        
    }
    
    
    
    ///账号路径
    private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
    
    
    func loadAcessToken(code: String, completion: (error: NSError?)->()){
        ///获取accessToken的url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        ///拼接参数
        let parameters = [
            
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
            
        ]
        ///POST发送请求
        HJNetWorkTool.sharedInstance.requestPOST(urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil{
                
                completion(error: error)
                return
            }
        
            
            
            self.userAccount = HJUserAccount(dict: result!)
            
            ///保存到沙盒
            
            self.saveUserAccount()
            
            ///通知控制器保存完成
            
            completion(error: nil)
        
        }
        
        

   }
        func loadUserInfo(completion: (error: NSError?) -> ()){
        ///获得URL
            let urlString = "https://api.weibo.com/2/users/show.json"
        ///拼接参数
            
            let parameters: [String: AnyObject] = [
                "access_token": userAccount!.access_token!,
                
                "uid": userAccount!.uid!
                
            ]
    
        ///GET的发送请求

      HJNetWorkTool.sharedInstance.afnMessage.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
        
         let dict = result as? [String: AnyObject]
        
        self.userAccount?.screen_name = dict?["screen_name"] as?String
        self.userAccount?.avatar_large = dict?["avatar_large"]as?String
            ///保存到沙盒
            self.saveUserAccount()
            //通知控制器保存完成
            completion(error: nil)
        
        
        }) { (_, error) -> Void in
            //通知控制器保存出现错误
            completion(error: error)
            
            }
        
        
    
    
    }
    
    
    
    //保存模型到沙盒
    private func saveUserAccount(){
        
        if userAccount != nil {
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
            
        }
    }
    
    ///从沙盒加载数据
    private func loadUserAccount() -> HJUserAccount? {
        
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? HJUserAccount
        ///判断是否过期
        
        if userAccount != nil && userAccount?.expiredDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            
            return userAccount
        }
        
        
        return nil
        
    }
    
    
}
